package org.ibase4j.assistant;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.ibase4j.core.base.BaseService;
import org.ibase4j.model.SysZhongZheng;
import org.springframework.beans.factory.annotation.Autowired;

public class PaQu extends BaseService<SysZhongZheng> implements ServletContextListener {
	private boolean flag = false;

	@Autowired
	// SysZhongMapper sysZhongMapper;

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		CrawlingCronTrigger cronRun = new CrawlingCronTrigger();
		System.out.println("output");
		try {

			// cronRun.run();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		Runnable runnable = new Runnable() {
			public void run() {
				try {
					// 更新日线
					// captureHtml("http://hq.sinajs.cn/etag.php?_=1498530357177&list=sh000905");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
		service.scheduleAtFixedRate(runnable, 1, 600, TimeUnit.SECONDS);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
	}

	private void captureHtml(String strURL) throws Exception {
		URL url = new URL(strURL);
		URLConnection context = url.openConnection();
		InputStream in = context.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(in, "gbk"));
		String line = "";
		StringBuilder contentBuf = new StringBuilder();
		while ((line = br.readLine()) != null) {
			contentBuf.append(line);
		}
		if (contentBuf != null && contentBuf.length() != 0) {
			String buf = contentBuf.toString();
			String[] kline = buf.split(",");
			String open = kline[1];
			String high = kline[4];
			String close = kline[3];
			String low = kline[5];
			String ymd = kline[30];
			double openvalue = Double.valueOf(open);
			double highvalue = Double.valueOf(high);
			double closevalue = Double.valueOf(close);
			double lowvalue = Double.valueOf(low);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(ymd);
			Update(openvalue, highvalue, closevalue, lowvalue, date);
		}

	}

	public void Update(double open, double high, double close, double low, Date ymd) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		int hours = date.getHours();
		int minutes = date.getMinutes();
		String all = hours + "" + minutes;
		int alls = Integer.parseInt(all);
		Date selecYMD = selecYMD();
		// 判断是否是周六日
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		// 如果是周六日，只更新日期
		if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
			if (!flag) {
				addRecord(date);
				flag = true;
			}
		} else {
			if (alls >= 930) {
				if (!isSameDate(selecYMD, ymd) && !flag) {
					addRecord(open, high, close, low, ymd);
					flag = true;
					System.out.println("zengjia");
				} else {
					updateRecord(open, high, close, low, ymd);
					System.out.println("gengxin");
				}
			}
		}

	}

	private void addRecord(Date date) {
		String sql = "insert into sys_zhong(daydate) values(?) ";
		conn = JDBCUtil.getConnection();
		java.sql.Date date1 = new java.sql.Date(date.getTime());
		try {
			pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			pstmt.setDate(1, date1);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.closeAll();
		}
	}

	private Connection conn = null; // 数据库连接
	private PreparedStatement pstmt = null; // 数据库操作

	@SuppressWarnings("deprecation")
	private Date selecYMD() {
		String sql = "select max(daydate) daydate from sys_zhong ";
		conn = JDBCUtil.getConnection();
		java.sql.Date datesql = null;
		try {
			Statement state = conn.createStatement();
			// 执行查询并返回结果集
			ResultSet rs = state.executeQuery(sql);
			while (rs.next()) {
				datesql = rs.getDate(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.closeAll();
		}
		// int hours = datesql.getHours();
		// int minutes = datesql.getMinutes();
		// String daydate = hours+""+minutes;
		// int intday = Integer.parseInt(daydate);
		java.util.Date d = new java.util.Date(datesql.getTime());
		return d;

	}

	private void addRecord(double open, double high, double close, double low, Date ymd) {
		String sql = "insert into sys_zhong(daydate,openv,high,low,close) values(?,?,?,?,?) ";
		conn = JDBCUtil.getConnection();
		java.sql.Date date = new java.sql.Date(ymd.getTime());
		try {
			pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			pstmt.setDate(1, date);
			pstmt.setDouble(2, open);
			pstmt.setDouble(3, high);
			pstmt.setDouble(4, low);
			pstmt.setDouble(5, close);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCUtil.closeAll();
		}
	}

	private void updateRecord(double open, double high, double close, double low, Date ymd) {
		String sqlString = "update sys_zhong set openv =?,high =?,close =?,low =?  where daydate =?";
		conn = JDBCUtil.getConnection();
		try {
			pstmt = conn.prepareStatement(sqlString);
			java.sql.Date date = new java.sql.Date(new Date().getTime());
			pstmt.setDouble(1, open);
			pstmt.setDouble(2, high);
			pstmt.setDouble(3, close);
			pstmt.setDouble(4, low);
			pstmt.setDate(5, date);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.closeAll();
		}

	}

	private static boolean isSameDate(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);
		boolean isSameYear = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
		boolean isSameMonth = isSameYear && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
		boolean isSameDate = isSameMonth && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
		return isSameDate;
	}
}
